﻿using System;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using vsm.WebControls;
using Microsoft.VisualBasic.FileIO;
using IFRS.DataAccess.DAL;
using IFRS.Models;
using System.Collections.Generic;

namespace IFRS.Web
{
    public class PageBase : Page
    {

        #region "---------- Property -----------"

        private ADUSER _ADUSER = null;
        private ADUSER ADUSER
        {
            get
            {
                if (_ADUSER == null)
                {
                    _ADUSER = new ADUSER();
                }

                return _ADUSER;
            }
        }

        protected string MenuTitleBar
        {
            get
            {
                Label lblMenuName = (Label)this.Master.FindControl("lblMenuName");
                return (lblMenuName == null) ? string.Empty : lblMenuName.Text;
            }
            set
            {
                Label lblMenuName = (Label)this.Master.FindControl("lblMenuName");
                if (lblMenuName != null)
                    lblMenuName.Text = value;
            }
        }

        #endregion

        #region "---------- Events -------------"

        protected override void OnLoad(EventArgs e)
        {
            Page.ClientScript.RegisterHiddenField("__hdnSysHostURL", vsm.Common.Utility.URLHelper.GetSiteRoot());

            base.OnLoad(e);
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            this.CheckUserPermission();
        }

        protected override void OnInitComplete(EventArgs e)
        {
            base.OnInitComplete(e);

            //if (string.IsNullOrEmpty(SessionManager.IFRS_USER_ID))
            //{
            //    Response.Redirect("~/Login.aspx");
            //}
        }

        protected override void OnError(EventArgs e)
        {
            Exception ex = HttpContext.Current.Server.GetLastError();

            HttpContext ctx = HttpContext.Current;

            Exception exception = ctx.Server.GetLastError();

            string errorInfo =
            "-----------------------------Error url-------------------------------------" + Environment.NewLine + ctx.Request.Url.ToString() + Environment.NewLine +
            "---------------------------------------------------------------------------" + Environment.NewLine +
            "" + Environment.NewLine +
            "---------------------------Error message---------------------------------" + Environment.NewLine + exception.Message + Environment.NewLine +
            "---------------------------------------------------------------------------" + Environment.NewLine +
            "" + Environment.NewLine +
            "-----------------------------Error line-------------------------------------" + Environment.NewLine + exception.StackTrace + Environment.NewLine +
            "--------------------------------------------------------------------------";

            Log.logger.Error(ctx.Request.Url.ToString(), ex);
            base.OnError(e);
        }

        #endregion

        #region "---------- Methods ------------"

        protected void ClearInputControls(PlaceHolder plcInputContainer)
        {
            foreach (Control ctrl in plcInputContainer.Controls)
            {
                if (ctrl is TextBox)
                {
                    ((TextBox)ctrl).Text = string.Empty;
                }
                else if (ctrl is DropDownList)
                {
                    ((DropDownList)ctrl).SelectedIndex = -1;
                }
                else if (ctrl is HtmlSelect)
                {
                    ((HtmlSelect)ctrl).SelectedIndex = -1;
                }
                else if (ctrl is RadioButton)
                {
                    ((RadioButton)ctrl).Checked = false;
                }
                else if (ctrl is HtmlInputCheckBox)
                {
                    ((HtmlInputCheckBox)ctrl).Checked = false;
                }
            }

        }
        protected void JS_Alert( string Message, string Location = "")
        {
            string ex_key = string.Format("{0}_{1}", "ALERT_FC", DateTime.Now.Ticks);
            string ex_script = string.Format("alert('{0}');", CleanScript(Message));
            if (!string.IsNullOrEmpty(Location))
            {
                ex_script += string.Format("window.location = '{0}';", Location.Trim());
            }
            this.ClientScript.RegisterStartupScript(this.GetType(), ex_key, ex_script, true);
        }
        protected string CleanScript(string script)
        {

            if (string.IsNullOrEmpty(script))
                script = string.Empty;

            script = script.Replace("'", "\\'");
            script = script.Replace("\"", "\\'");
            //script = script.Replace(Constants.vbCrLf, "\\n");

            return script;

        }
        protected void SetControlReadOnly(PlaceHolder plcReadOnly)
        {
            foreach (Control ctrl in plcReadOnly.Controls)
            {
                if (ctrl is Button)
                {
                    ((Button) ctrl).Enabled = false;
                }
                if (ctrl is TextBox)
                {
                    ((TextBox)ctrl).Attributes["readOnly"] = "true";
                    ((TextBox)ctrl).BackColor = System.Drawing.Color.FromArgb(224, 224, 224);
                    ((TextBox) ctrl).CssClass = "NormalTextBox";
                }
                else if (ctrl is DropDownList)
                {
                    ((DropDownList)ctrl).Enabled = false;
                    ((DropDownList)ctrl).BackColor = System.Drawing.Color.FromArgb(224, 224, 224);
                    ((DropDownList)ctrl).CssClass = "NormalTextBox";
                }
                else if (ctrl is RadioButton)
                {
                    ((RadioButton)ctrl).Attributes["disabled"] = "true";
                    // ((RadioButton)ctrl).BackColor = System.Drawing.Color.FromArgb(224, 224, 224);
                }
                else if (ctrl is RadioButtonList)
                {
                    //((RadioButtonList)ctrl).Attributes["readOnly"] = "true";
                    //((RadioButtonList)ctrl).BackColor = System.Drawing.Color.FromArgb(224, 224, 224);
                    //((RadioButtonList) ctrl).Enabled = false;

                    ((RadioButtonList)ctrl).Attributes["readOnly"] = "true";
                    ((RadioButtonList)ctrl).Enabled = false;
                }
                else if (ctrl is Image)
                {
                    ((Image)ctrl).Attributes["disabled"] = "true";
                }
                else if (ctrl is CheckBox)
                {
                    ((CheckBox) ctrl).Enabled = false;
                }
            }
        }
        protected void SetControlReadOnly(Control ctrl)
        {
            if (ctrl is Button)
            {
                ((Button)ctrl).Enabled = false;
            }
            if (ctrl is TextBox)
            {
                ((TextBox)ctrl).Attributes["readOnly"] = "true";
                ((TextBox)ctrl).BackColor = System.Drawing.Color.FromArgb(224, 224, 224);
            }
            else if (ctrl is DropDownList)
            {
                ((DropDownList)ctrl).Enabled = false;
                ((DropDownList)ctrl).BackColor = System.Drawing.Color.FromArgb(224, 224, 224);
            }
            else if (ctrl is RadioButton)
            {
                ((RadioButton)ctrl).Attributes["disabled"] = "true";
                // ((RadioButton)ctrl).BackColor = System.Drawing.Color.FromArgb(224, 224, 224);
            }
            else if (ctrl is RadioButtonList)
            {
                ((RadioButtonList)ctrl).Attributes["readOnly"] = "true";
                ((RadioButtonList)ctrl).BackColor = System.Drawing.Color.FromArgb(224, 224, 224);
            }
            else if (ctrl is Image)
            {
                ((Image)ctrl).Attributes["disabled"] = "true";
            }
            else if (ctrl is CheckBox)
            {
                ((CheckBox)ctrl).Enabled = false;
            }
        }

        protected void SetConfirmButton(Button btnButton, string strCommand)
        {
            btnButton.Attributes["OnClick"] = "if(!confirm(\"" + strCommand + "\")) return false;";
        }

        protected void SetConfirmLinkButton(LinkButton lnkButton, string strMessage)
        {
            lnkButton.Attributes["OnClick"] = "if(!confirm(\"" + strMessage + "\")) return false;";
        }

        protected DataTable GetDataTabletFromCSVFile(string csv_file_path)
        {
            DataTable csvData = new DataTable();
            try
            {
                using (TextFieldParser csvReader = new TextFieldParser(csv_file_path))
                {
                    csvReader.SetDelimiters(new string[] { "," });
                    csvReader.HasFieldsEnclosedInQuotes = true;
                    string[] colFields = csvReader.ReadFields();
                    foreach (string column in colFields)
                    {
                        DataColumn datecolumn = new DataColumn(column);
                        datecolumn.AllowDBNull = true;
                        csvData.Columns.Add(datecolumn);
                    }
                    while (!csvReader.EndOfData)
                    {
                        string[] fieldData = csvReader.ReadFields();
                        //Making empty value as null
                        for (int i = 0; i < fieldData.Length; i++)
                        {
                            if (fieldData[i] == "")
                            {
                                fieldData[i] = null;
                            }
                        }
                        csvData.Rows.Add(fieldData);
                    }
                }
            }
            catch (Exception ex)
            {

            }
            return csvData;
        }

        private void CheckUserPermission()
        {
            if (Request.QueryString["pid"] != null)
            {
                if (SessionManager.IFRS_ROLE_ID != -1)
                {
                    if (string.IsNullOrEmpty(SessionManager.IFRS_PROGRAM_ID))
                    {
                        SessionManager.IFRS_PROGRAM_ID = Request.QueryString["pid"];
                        this.SetUserPermission();
                    }
                    else if (SessionManager.IFRS_PROGRAM_ID != Request.QueryString["pid"])
                    {
                        SessionManager.IFRS_PROGRAM_ID = Request.QueryString["pid"];
                        this.SetUserPermission();
                    }
                }
                else
                {
                    Session.Remove("IFRS_PROGRAM_ID");
                }
            }
        }

        private void SetUserPermission()
        {
            DataTable dtADUSER = ADUSER.SEARCH_BYID_ROLEGROUPMENU_USER(SessionManager.IFRS_ROLE_ID,Request.QueryString["pid"].AsInt32());
            List<PermissionUser> PermissionUser = new List<PermissionUser>();
            ConvertHelper.ConvertDataTableToObject(dtADUSER, PermissionUser);
            if (dtADUSER.Rows.Count > 0)
              {
                  SessionManager.IFRS_EDIT = PermissionUser[0].IsEdit;
                  SessionManager.IFRS_ADD = PermissionUser[0].IsAdd;
                  SessionManager.IFRS_DELETE = PermissionUser[0].IsDelete;
                  SessionManager.IFRS_VIEW = PermissionUser[0].IsView;
              }
        }

        #region === Validation ===

        public bool ValidationDate(DateTime startDate , DateTime endDate)
        {
            return startDate.Date <= endDate.Date;
        }
        public bool ValidationDateNotEqual(DateTime startDate, DateTime endDate)
        {
            return startDate.Date < endDate.Date;
        }

        #endregion

        #endregion
    }

    public class PopupBase : PageBase
    {
        protected string PopupTitle
        {
            get
            {
                Label lblPopupTitle = (Label)this.Master.FindControl("lblPageTitle");
                return lblPopupTitle.Text;
            }
            set
            {
                Label lblPopupTitle = (Label)this.Master.FindControl("lblPageTitle");
                lblPopupTitle.Text = value;
            }
        }

        protected string PopupBar1
        {
            get
            {
                Label lblTitleBar1 = (Label)this.Master.FindControl("lblTitleBar1");
                return lblTitleBar1.Text;
            }
            set
            {
                Label lblTitleBar1 = (Label)this.Master.FindControl("lblTitleBar1");
                lblTitleBar1.Text = value;
            }
        }

        protected string PopupBar2
        {
            get
            {
                Label lblTitleBar2 = (Label)this.Master.FindControl("lblTitleBar2");
                return lblTitleBar2.Text;
            }
            set
            {
                Label lblTitleBar2 = (Label)this.Master.FindControl("lblTitleBar2");
                lblTitleBar2.Text = value;
            }
        }

        private PopupToolbar _VSMToolbar = null;
        protected PopupToolbar VSMToolbar
        {
            get
            {
                if (_VSMToolbar == null)
                    _VSMToolbar = (PopupToolbar)this.Master.FindControl("VSMToolbar");
                return _VSMToolbar;
            }
        }

        #region "---------- Methods ------------"

        protected void CloseWindow()
        {
            Page.ClientScript.RegisterStartupScript(Page.GetType(), "js_CloseWindow", "window.close();", true);
        }

        #endregion

    }

    public static class Extension
    {
        public static string Sorting(this GridViewSortEventArgs e, string sortingExpression,
            SortDirection? sortingDirection)
        {
            //SortingDirection == SortDirection.Ascending ? SortDirection.Descending : SortDirection.Ascending;
            if (sortingExpression == string.Empty) return string.Empty;
            switch (sortingDirection)
            {
                case null:
                    return string.Format("{0} {1}", sortingExpression, "ASC");
                case SortDirection.Ascending:
                    return string.Format("{0} {1}", sortingExpression, "ASC");
                default:
                    return string.Format("{0} {1}", sortingExpression, "DESC");
            }
        }

        public static void SaveViewState<T>(this System.Web.UI.Page page, T obj, StateBag viewState, string suffix = "")
        {
            var baseType = page.GetType().BaseType;
            if (baseType == null) return;
            var name = baseType.Name + "_" + obj.GetType().Name;
            if (suffix != string.Empty)
                name += "_" + suffix;
            viewState[name] = obj;
        }

        public static T LoadViewState<T>(this System.Web.UI.Page page, T obj, StateBag viewState, string suffix = "")
        {
            var baseType = page.GetType().BaseType;
            var name = baseType.Name + "_" + obj.GetType().Name;
            if (suffix != string.Empty)
                name += "_" + suffix;

            return (T)viewState[name]; //(T)Convert.ChangeType(viewState[name], typeof(T));
        }
    }
}